package com.applancer.fragment;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.applancer.dataprovider.DataProvider;
import com.applancer.dataprovider.DataType.Type;
import com.applancer.dataprovider.DataUtil;
import com.applancer.form.CharacterField;
import com.applancer.form.NormalField;
import com.applancer.model.UserModel;
import com.applancer.nativecmsflip.R;
import com.applancer.nativecmsflip.RegisterActivity;
import com.applancer.nativecmsflip.UserActivity;
import com.applancer.parser.GeneralParser;
import com.applancer.provider.ContentManager;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class LoginFragment extends Fragment {

	protected View contentView;

	protected EditText userid;
	protected EditText password;
	protected Button bt_login;
	protected Button bt_register;
	protected DataProvider dataProvider;
	protected GeneralParser parser;

	public static final String MYPREFERENCES = "LoginRef";
	public static final String LOG_USERNAME = "login_username";
	public static final String LOG_PASS = "login_pass";
	public static final String LOG_STATE = "login_state";
	public static final String LOG_EMAIL = "login_email";
	public static final String LOG_URL = "login_url";

	public SharedPreferences sharedpreferences;

	public ProgressBar indicator_login;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.login_fragment, null);
		return contentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		initial();
		execution();

	}

	public void initializeFormFields() {

		((UserActivity) contentView.getContext())
				.addValidator(new CharacterField(userid));
		((UserActivity) contentView.getContext()).addValidator(new NormalField(
				password));
	}

	private void initial() {
		sharedpreferences = contentView.getContext().getSharedPreferences(
				MYPREFERENCES, Context.MODE_PRIVATE);
		bt_login = (Button) contentView.findViewById(R.id.account_user_login);
		bt_register = (Button) contentView
				.findViewById(R.id.account_user_register);

		dataProvider = new DataProvider(contentView.getContext());
		parser = GeneralParser.createInstance(Type.User);

		userid = (EditText) contentView.findViewById(R.id.account_user_name);
		password = (EditText) contentView.findViewById(R.id.account_user_pass);

		indicator_login = (ProgressBar) contentView
				.findViewById(R.id.indicator_login);
	}

	private void execution() {

		indicator_login.setVisibility(View.GONE);

		bt_login.setOnClickListener(loginEvent);
		bt_register.setOnClickListener(registerEvent);
		if (sharedpreferences.contains(LOG_USERNAME)) {
			userid.setText(sharedpreferences.getString(LOG_USERNAME, ""));
		}

		if (sharedpreferences.contains(LOG_PASS)) {
			password.setText(sharedpreferences.getString(LOG_PASS, ""));
		}

	}

	OnClickListener loginEvent = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (((UserActivity) contentView.getContext()).validateForm() == false) {
				return;
			}
			// everything is good

			signup(userid.getText().toString(), password.getText().toString());
		}
	};

	public void signup(String userid, String password) {

		indicator_login.setVisibility(View.VISIBLE);
		dataProvider.login(userid, password, handler);
	}

	OnClickListener registerEvent = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent(contentView.getContext(),
					RegisterActivity.class);
			startActivity(intent);
			((Activity) contentView.getContext()).overridePendingTransition(
					R.anim.slide_left_in, R.anim.slide_left_out);
		}
	};

	AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {
			String result = new String(response);

			try {
				JSONObject jsonObj = new JSONObject(result);

				UserModel user = (UserModel) parser.parseModel(jsonObj
						.getJSONObject(DataUtil.userProfile));
				user.setPass(password.getText().toString());

				ContentManager manager = ContentManager.getInstance();
				manager.currentUser = user;

				Editor editor = sharedpreferences.edit();
				editor.putString(LOG_USERNAME, user.getUserName());
				editor.putString(LOG_PASS, password.getText().toString());
				editor.putBoolean(LOG_STATE, true);
				editor.putString(LOG_EMAIL, user.getEmail());
				editor.putString(LOG_URL, user.getUrl());
				editor.commit();

				((UserActivity) contentView.getContext()).change2profile();

			} catch (Exception e) {

			}

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			
			
			
			Log.d("login", "fail");
			
			
		}

		public void onFinish() {
			indicator_login.setVisibility(View.GONE);
		};
	};
}
